package org.cainiao.api.lark.impl.reactive;

import lombok.AllArgsConstructor;
import org.cainiao.api.lark.impl.reactive.authenticateandauthorize.getaccesstokens.WebClientGetAccessTokens;
import org.cainiao.api.lark.impl.reactive.docs.space.folder.WebClientFolder;
import org.cainiao.api.lark.impl.util.converter.LarkFieldNameMapResponseConverter;
import org.cainiao.api.lark.impl.util.converter.ResponseConverter;
import org.cainiao.api.lark.reactive.LarkApi;
import org.cainiao.api.lark.reactive.authenticateandauthorize.AuthenticateAndAuthorize;
import org.cainiao.api.lark.reactive.docs.Docs;
import org.cainiao.api.lark.reactive.docs.space.Space;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.function.Supplier;

/**
 * LarkApi 的默认实现
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@AllArgsConstructor
public class WebClientLarkApi implements LarkApi {

    private final WebClient webClient;
    /**
     * 飞书为："https://open.feishu.cn/open-apis"
     * 但也可能是调用授权中心资源服务器
     */
    private final String baseUrl;
    private final Supplier<String> appAccessTokenProvider;
    private final Supplier<String> accessTokenProvider;
    private final ResponseConverter responseConverter;

    @Override
    public AuthenticateAndAuthorize authenticateAndAuthorize() {
        return () -> new WebClientGetAccessTokens(webClient, baseUrl, responseConverter);
    }

    @Override
    public Docs docs() {
        return () -> (Space) () -> new WebClientFolder(webClient, baseUrl, responseConverter);
    }

    public WebClientLarkApi(WebClient webClient, String baseUrl,
                            Supplier<String> appAccessTokenProvider, Supplier<String> accessTokenProvider) {
        this.webClient = webClient;
        this.baseUrl = baseUrl;
        this.appAccessTokenProvider = appAccessTokenProvider;
        this.accessTokenProvider = accessTokenProvider;
        this.responseConverter = new LarkFieldNameMapResponseConverter();
    }

    public WebClientLarkApi(WebClient webClient, String baseUrl, ResponseConverter responseConverter) {
        this.webClient = webClient;
        this.baseUrl = baseUrl;
        this.appAccessTokenProvider = null;
        this.accessTokenProvider = null;
        this.responseConverter = responseConverter;
    }
}
